package com.aduerr.v1shouyin.mvp.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Looper;
import androidx.annotation.NonNull;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bertsir.zbar.utils.QRUtils;
import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.entity.ErwewimaResultEntity;
import com.aduerr.v1shouyin.entity.PayStateEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.base.BaseActivity;
import com.aduerr.v1shouyin.mvp.presenter.CreatErweimaPresenter;
import com.aduerr.v1shouyin.mvp.view.CreatErweimaView;
import com.aduerr.v1shouyin.util.NetUtils;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

public class ErweimaActivity extends BaseActivity<CreatErweimaView,
        CreatErweimaPresenter> implements CreatErweimaView {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.img_erweima)
    ImageView imgErweima;
    private String realymoney;
    private String beizhu;

    private Date startDate;
    private Date endDate;
    private long looptime = 1 * 90 * 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_erweima);
        ButterKnife.bind(this);
        initUI();
        initData();
    }

    @NonNull
    @Override
    public CreatErweimaPresenter createPresenter() {
        return new CreatErweimaPresenter(App.getApp());
    }


    public void initUI() {
        tvTitle.setText("扫码收款");
    }


    public void initData() {
        realymoney = getIntent().getStringExtra("realymoney");
        beizhu = getIntent().getStringExtra("beizhu");
        if(realymoney != null) {
            tvMoney.setText(realymoney);
        }
        getPresenter().getErweima(ErweimaActivity.this, realymoney, beizhu);
    }


    public void showProgress() {

    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {

    }

    @OnClick({R.id.img_back, R.id.tv_back})
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onCreatErweima(ErwewimaResultEntity erwewimaResultEntity) {
        int success = erwewimaResultEntity.getSuccess();
        if(success == 1) {
            //获取订单列表

            startDate = new Date(System.currentTimeMillis());
            payState(erwewimaResultEntity.getOrderid());

            String qrcodeurl = erwewimaResultEntity.getUrl();
            if(!TextUtils.isEmpty(qrcodeurl)) {
                Bitmap qrCode = QRUtils.getInstance().createQRCode(qrcodeurl);
                imgErweima.setImageBitmap(qrCode);
            } else {
                ToastUtils.showToast(ErweimaActivity.this,
                        erwewimaResultEntity.getErrMsg());
            }
        } else if(success == -100 | success == -200) {
            //// TODO: 2017/12/9 0009 绑定guid  界面
            SharedPreferencesUtils.remove(ErweimaActivity.this, "autologin");
            SharedPreferencesUtils.remove(ErweimaActivity.this, "remberpassword");
            startActivity(new Intent(ErweimaActivity.this, BangGuidActivity.class));
            finish();
        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
            //// TODO: 2017/12/9 0009 去登录的界面
            com.blankj.utilcode.util.ToastUtils.showShortSafe(erwewimaResultEntity.getErrMsg());
            SharedPreferencesUtils.remove(ErweimaActivity.this, "autologin");
            SharedPreferencesUtils.remove(ErweimaActivity.this, "remberpassword");
            startActivity(new Intent(ErweimaActivity.this, LoginActivity.class));
            finish();
        } else {
            ToastUtils.showToast(ErweimaActivity.this,
                    "" + erwewimaResultEntity.getErrMsg());
        }
    }

    /**
     * 获取支付状态
     *
     * @param
     */
    private void payState(String orderid) {
        if(TextUtils.isEmpty(orderid)) return;
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("orderid", orderid);
        APIRetrofit.getAPIService().payState(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PayStateEntity>() {
                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull PayStateEntity payStateEntity) {
//                        if (Tools.isAvailable(payStateEntity)) return;
                        int success = payStateEntity.getSuccess();
                        if(success == 1) {
                            Intent intent = new Intent(ErweimaActivity.this,
                                    ResultActivity.class);
                            intent.putExtra("sucess", "10");
                            intent.putExtra("beizhu", beizhu);
                            intent.putExtra("money", realymoney);
                            intent.putExtra("orderid", orderid);
                            intent.putExtra(Constants.PAYSTATEENTITY, payStateEntity);
                            startActivity(intent);
                            finish();
                        } else {
                            endDate = new Date(System.currentTimeMillis());
                            long diff = endDate.getTime() - startDate.getTime();
                            if(diff > looptime) {
                                if(looptime == 0) {
                                    return;
                                }
                                ToastUtils.showToast(App.getApp(),
                                        getResources().getString(R.string.text_pay_overtime));
                                finish();
                                return;
                            }


                            try {
                                TimerTask task = new TimerTask() {
                                    @Override
                                    public void run() {
                                        /**
                                         *要执行的操作
                                         */
                                        Looper.prepare();
                                        payState(orderid);
                                        Looper.loop();
                                    }
                                };
                                Timer timer = new Timer();
                                timer.schedule(task, 2000);//2秒后执行TimeTask的run方法
                            } catch(Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(ErweimaActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(ErweimaActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
                            Toast.makeText(ErweimaActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(ErweimaActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }


    @Override
    protected void onDestroy() {
        looptime = 0;
        super.onDestroy();
    }

    @Override
    protected void onNetworkDisConnected() {
        ToastUtils.showToast(context, "网络开小差了,请检查网络");
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
        ToastUtils.showToast(context, type.name());
    }
}
